package com.kitty.record.kittyalgorithm.audition;

import java.util.Arrays;

/**
 * 三合一。
 * 描述如何只用一个数组来实现三个栈。
 * 你应该实现push(stackNum, value)、pop(stackNum)、isEmpty(stackNum)、peek(stackNum)方法。
 * stackNum表示栈下标，value表示压入的值。
 * 构造函数会传入一个stackSize参数，代表每个栈的大小。
 *
 * 示例1:
 * 输入：
 * ["TripleInOne", "push", "push", "pop", "pop", "pop", "isEmpty"]
 * [[1], [0, 1], [0, 2], [0], [0], [0], [0]]
 * 输出：
 * [null, null, null, 1, -1, -1, true]
 * 说明：当栈为空时`pop, peek`返回-1，当栈满时`push`不压入元素。
 *
 * 示例2:
 * 输入：
 * ["TripleInOne", "push", "push", "push", "pop", "pop", "pop", "peek"]
 * [[2], [0, 1], [0, 2], [0, 3], [0], [0], [0], [0]]
 * 输出：
 * [null, null, null, null, 2, 1, -1, -1]
 * @Author SHEN
 * @Date 2020/12/18
 */
public class LeetCode0301 {
    public static void main(String[] args) {
        TripleInOne tripleInOne = new TripleInOne(5);

        tripleInOne.push(0,5);
        tripleInOne.push(0,5);
        tripleInOne.push(0,5);
        tripleInOne.push(0,5);
        tripleInOne.push(0,5);

        tripleInOne.push(1,6);
        tripleInOne.push(1,6);
        tripleInOne.push(1,6);
        tripleInOne.push(1,6);
        tripleInOne.push(1,6);

        tripleInOne.push(2,7);
        tripleInOne.push(2,7);
        tripleInOne.push(2,7);
        tripleInOne.push(2,7);
        tripleInOne.push(2,7);

        System.out.println(tripleInOne.toString());

    }


    private static class TripleInOne {

        private int[] stack;

        private int[] top;

        private int stackSize;

        public TripleInOne(int stackSize) {
            this.stackSize = stackSize;
            this.stack = new int[stackSize*3];
            this.top = new int[]{0,1,2};
        }

        public void push(int stackNum, int value) {
            //判断栈是否满了
            //只有当所选择的栈的下标到达指定位置，说明栈满了；
            //当stack的长度为12时，top[0] = 12;top[1] = 13;top[2] = 14时说明0，1，2三个栈已经满了；
            if((this.top[stackNum] - stackNum)/3 == stackSize){
                return;
            }
            this.stack[this.top[stackNum]] = value;
            this.top[stackNum] +=3;
        }

        public int pop(int stackNum) {
            if(this.isEmpty(stackNum)){
                return -1;
            }
            this.top[stackNum] -= 3;
            int val = this.stack[top[stackNum]];
            return val;
        }

        public int peek(int stackNum) {
            if(this.isEmpty(stackNum)){
                return -1;
            }
            int val = this.stack[top[stackNum] - 3];
            return val;
        }

        public boolean isEmpty(int stackNum) {
            if(top[stackNum] < 3){
                return true;
            }
            return false;
        }

        @Override
        public String toString() {
            return "TripleInOne{" +
                    "stack=" + Arrays.toString(stack) +
                    '}';
        }
    }
}

